/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sunsite.dao;

import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import sunsite.po.Message;
import sunsite.po.Usr;


/**
 *
 * @author mg
 */
public class MessageDaoImpl extends HibernateDaoSupport implements MessageDao {

    private int maxResult = 5;

    public void addMessage(Message m) throws DataAccessException {
        getHibernateTemplate().save(m);
    }

    public List<Message> getMessages(final int pageNow) throws DataAccessException {
        List<Message> list = getHibernateTemplate().executeFind(new HibernateCallback() {

            public Object doInHibernate(Session arg0) throws HibernateException, SQLException {
                Query q = arg0.createQuery("from Message as m order by m.mesTime desc");
                q.setFirstResult((pageNow - 1) * maxResult);
                q.setMaxResults(maxResult);
                return q.list();
            }
        });
        if(list!=null&&list.size()>0)
            return list;
        else
            return null;
    }

    public int getPageCount() throws DataAccessException {
        int pageCount = 0;
        int count = ((Long)(getHibernateTemplate().executeFind(new HibernateCallback() {

            public Object doInHibernate(Session arg0) throws HibernateException, SQLException {
                Query q = arg0.createQuery("select count(m.mesId) from Message as m");
                return q.list();
            }
        }).get(0))).intValue();
        if(count <= maxResult){
            pageCount = 1;
            return pageCount;
        }
        if(count % maxResult > 0){
            pageCount = count/maxResult + 1;
        }else{
            pageCount = count/maxResult;
        }
        return pageCount;
    }

}
